package com.gupaoedu.design.template;

import com.gupaoedu.design.template.mapper.RowMapper;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * <p></p>
 *
 * @author Andy
 * @date 2018/3/13.
 */
public class JdbcTemplate {

    private DataSource dataSource;
    public JdbcTemplate(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    private Connection getConnection() throws Exception{
        return this.dataSource.getConnection();
    }

    private PreparedStatement prepareStatement(Connection conn, String sql) throws SQLException {
        return conn.prepareStatement(sql);
    }

    private void closeResultSet(ResultSet rs) throws SQLException {
        rs.close();
    }

    private void closePreparedStatement(PreparedStatement prst) throws SQLException {
        prst.close();
    }

    private void closeConnection(Connection conn) throws SQLException {
        //放回数据连接池中
    }

    private List<?> processResult(ResultSet rs, RowMapper rowMapper) throws SQLException {
        List<Object> list = new ArrayList<Object>();
        int rowNum = 1;
        //4、分析结果集
        while (rs.next()) {
            list.add(rowMapper.mapRow(rs, rowNum++));
        }
        return list;
    }

    public List<?> executeQuery(String sql, RowMapper rowMapper) {
        try {
            //1、创建JDBC的连接
            Connection conn = this.getConnection();
            //2、创建语句集
            PreparedStatement prst = this.prepareStatement(conn, sql);
            //3、获取结果集
            ResultSet rs = prst.executeQuery();
            List<?> list = this.processResult(rs,rowMapper);
            //5、关闭结果集
            this.closeResultSet(rs);
            //6、关闭语句集
            this.closePreparedStatement(prst);
            //7、关闭连接
            this.closeConnection(conn);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
